<template>
  <div class="feedback-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">反馈管理</h1>
        <p class="page-subtitle">查看和回复活动反馈</p>
      </div>
      <div class="header-actions">
        <el-button @click="exportFeedbacks">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ stats.total }}</div>
            <div class="stat-label">总反馈</div>
          </div>
          <el-icon class="stat-icon"><ChatDotRound /></el-icon>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ stats.unread }}</div>
            <div class="stat-label">未读</div>
          </div>
          <el-icon class="stat-icon unread"><Bell /></el-icon>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ stats.replied }}</div>
            <div class="stat-label">已回复</div>
          </div>
          <el-icon class="stat-icon replied"><Check /></el-icon>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ stats.averageRating.toFixed(1) }}</div>
            <div class="stat-label">平均评分</div>
          </div>
          <el-icon class="stat-icon rating"><Star /></el-icon>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="关键词">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索反馈内容或学生姓名"
            clearable
            style="width: 250px"
            @keyup.enter="loadFeedbacks"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="活动">
          <el-select v-model="filters.activityId" placeholder="选择活动" clearable style="width: 200px">
            <el-option label="全部活动" value="" />
            <el-option 
              v-for="activity in activities" 
              :key="activity.id" 
              :label="activity.title" 
              :value="activity.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="类型">
          <el-select v-model="filters.type" placeholder="选择类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="活动体验" value="experience" />
            <el-option label="组织服务" value="service" />
            <el-option label="建议意见" value="suggestion" />
            <el-option label="投诉举报" value="complaint" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="评分">
          <el-select v-model="filters.rating" placeholder="选择评分" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="5星" value="5" />
            <el-option label="4星" value="4" />
            <el-option label="3星" value="3" />
            <el-option label="2星" value="2" />
            <el-option label="1星" value="1" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="选择状态" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="未读" value="unread" />
            <el-option label="已读" value="read" />
            <el-option label="已回复" value="replied" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="反馈时间">
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="loadFeedbacks">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilters">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 反馈列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <div class="header-title">
            <span>反馈列表</span>
            <el-tag v-if="pagination.total > 0" type="info" size="small">
              共 {{ pagination.total }} 条反馈
            </el-tag>
          </div>
          <div class="header-actions">
            <el-button @click="markAllAsRead" :disabled="stats.unread === 0">
              <el-icon><Check /></el-icon>
              全部标记已读
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="feedbacks.length === 0" class="empty-container">
        <el-empty description="暂无反馈" />
      </div>
      
      <!-- 反馈列表 -->
      <div v-else class="feedback-list">
        <div 
          v-for="feedback in feedbacks" 
          :key="feedback.id"
          class="feedback-item"
          :class="{ unread: feedback.status === 'unread' }"
          @click="viewFeedback(feedback)"
        >
          <div class="feedback-header">
            <div class="feedback-meta">
              <div class="student-info">
                <span class="student-name">{{ feedback.student?.name }}</span>
                <span class="student-id">{{ feedback.student?.studentId }}</span>
              </div>
              <div class="feedback-time">
                {{ formatDate(feedback.createTime, 'MM-DD HH:mm') }}
              </div>
            </div>
            <div class="feedback-status">
              <el-tag 
                v-if="feedback.status === 'unread'" 
                type="warning" 
                size="small"
              >
                未读
              </el-tag>
              <el-tag 
                v-else-if="feedback.status === 'replied'" 
                type="success" 
                size="small"
              >
                已回复
              </el-tag>
              <el-tag 
                v-else 
                type="info" 
                size="small"
              >
                已读
              </el-tag>
            </div>
          </div>
          
          <div class="feedback-content">
            <div class="activity-info">
              <span class="activity-title">{{ feedback.activity?.title }}</span>
              <el-tag size="small">{{ getTypeText(feedback.type) }}</el-tag>
            </div>
            
            <div class="feedback-rating">
              <el-rate
                :model-value="feedback.rating"
                disabled
                size="small"
                show-score
                text-color="#ff9900"
              />
            </div>
            
            <div class="feedback-text">
              {{ feedback.content }}
            </div>
            
            <div v-if="feedback.images && feedback.images.length > 0" class="feedback-images">
              <el-image
                v-for="(image, index) in feedback.images.slice(0, 3)"
                :key="index"
                :src="image"
                :preview-src-list="feedback.images"
                :initial-index="index"
                class="feedback-image"
                fit="cover"
              />
              <div v-if="feedback.images.length > 3" class="more-images">
                +{{ feedback.images.length - 3 }}
              </div>
            </div>
            
            <div v-if="feedback.reply" class="feedback-reply">
              <div class="reply-header">
                <el-icon><ChatDotRound /></el-icon>
                <span>您的回复：</span>
                <span class="reply-time">{{ formatDate(feedback.replyTime, 'MM-DD HH:mm') }}</span>
              </div>
              <div class="reply-content">{{ feedback.reply }}</div>
            </div>
          </div>
          
          <div class="feedback-actions">
            <el-button type="primary" size="small" text @click.stop="viewFeedback(feedback)">
              查看详情
            </el-button>
            <el-button 
              v-if="!feedback.reply"
              type="success" 
              size="small" 
              text 
              @click.stop="replyFeedback(feedback)"
            >
              回复
            </el-button>
            <el-button 
              v-if="feedback.status === 'unread'"
              type="info" 
              size="small" 
              text 
              @click.stop="markAsRead(feedback.id)"
            >
              标记已读
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="feedbacks.length > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadFeedbacks"
          @current-change="loadFeedbacks"
        />
      </div>
    </el-card>

    <!-- 查看反馈详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="反馈详情" 
      width="700px"
      :before-close="closeDetailDialog"
    >
      <div v-if="currentFeedback" class="feedback-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学生姓名">
            {{ currentFeedback.student?.name }}
          </el-descriptions-item>
          <el-descriptions-item label="学号">
            {{ currentFeedback.student?.studentId }}
          </el-descriptions-item>
          <el-descriptions-item label="活动名称" :span="2">
            {{ currentFeedback.activity?.title }}
          </el-descriptions-item>
          <el-descriptions-item label="反馈类型">
            {{ getTypeText(currentFeedback.type) }}
          </el-descriptions-item>
          <el-descriptions-item label="评分">
            <el-rate
              :model-value="currentFeedback.rating"
              disabled
              show-score
              text-color="#ff9900"
            />
          </el-descriptions-item>
          <el-descriptions-item label="反馈时间">
            {{ formatDate(currentFeedback.createTime, 'YYYY-MM-DD HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentFeedback.status)">
              {{ getStatusText(currentFeedback.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="反馈内容" :span="2">
            <div class="feedback-content-detail">
              {{ currentFeedback.content }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentFeedback.images && currentFeedback.images.length > 0" label="图片" :span="2">
            <div class="feedback-images-detail">
              <el-image
                v-for="(image, index) in currentFeedback.images"
                :key="index"
                :src="image"
                :preview-src-list="currentFeedback.images"
                :initial-index="index"
                class="detail-image"
                fit="cover"
              />
            </div>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentFeedback.reply" label="回复内容" :span="2">
            <div class="reply-content-detail">
              {{ currentFeedback.reply }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentFeedback.replyTime" label="回复时间">
            {{ formatDate(currentFeedback.replyTime, 'YYYY-MM-DD HH:mm:ss') }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDetailDialog">关闭</el-button>
          <el-button 
            v-if="!currentFeedback?.reply"
            type="success" 
            @click="replyFeedback(currentFeedback)"
          >
            回复
          </el-button>
          <el-button 
            v-if="currentFeedback?.status === 'unread'"
            type="primary" 
            @click="markAsRead(currentFeedback.id)"
          >
            标记已读
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 回复反馈对话框 -->
    <el-dialog 
      v-model="replyDialogVisible" 
      title="回复反馈" 
      width="600px"
    >
      <div v-if="currentFeedback" class="reply-form">
        <div class="original-feedback">
          <h4>原反馈内容：</h4>
          <div class="original-content">
            <div class="original-rating">
              <el-rate
                :model-value="currentFeedback.rating"
                disabled
                show-score
                text-color="#ff9900"
              />
            </div>
            <div class="original-text">{{ currentFeedback.content }}</div>
          </div>
        </div>
        
        <el-form :model="replyForm" label-width="80px">
          <el-form-item label="回复内容" required>
            <el-input 
              v-model="replyForm.content"
              type="textarea"
              :rows="6"
              placeholder="请输入回复内容"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmReply" :loading="replying">
            发送回复
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { formatDate } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import {
  Download,
  ChatDotRound,
  Bell,
  Check,
  Star,
  Search,
  Refresh
} from '@element-plus/icons-vue'

const loading = ref(false)
const replying = ref(false)
const detailDialogVisible = ref(false)
const replyDialogVisible = ref(false)

const stats = reactive({
  total: 0,
  unread: 0,
  replied: 0,
  averageRating: 0
})

const filters = reactive({
  keyword: '',
  activityId: '',
  type: '',
  rating: '',
  status: '',
  dateRange: null
})

const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

const replyForm = reactive({
  content: ''
})

const feedbacks = ref([])
const activities = ref([])
const currentFeedback = ref(null)

const getTypeText = (type) => {
  const textMap = {
    experience: '活动体验',
    service: '组织服务',
    suggestion: '建议意见',
    complaint: '投诉举报'
  }
  return textMap[type] || type
}

const getStatusType = (status) => {
  const typeMap = {
    unread: 'warning',
    read: 'info',
    replied: 'success'
  }
  return typeMap[status] || ''
}

const getStatusText = (status) => {
  const textMap = {
    unread: '未读',
    read: '已读',
    replied: '已回复'
  }
  return textMap[status] || status
}

const loadStats = async () => {
  try {
    const response = await api.get('/organizer/feedbacks/stats')
    const data = response.data.data
    
    Object.assign(stats, data)
    
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const loadActivities = async () => {
  try {
    const response = await api.get('/organizer/activities', {
      params: { size: 1000 }
    })
    
    activities.value = response.data.data?.data || []
    
  } catch (error) {
    console.error('加载活动列表失败:', error)
  }
}

const loadFeedbacks = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.current - 1,
      size: pagination.size,
      ...filters
    }
    
    // 处理日期范围
    if (filters.dateRange && filters.dateRange.length === 2) {
      params.startDate = filters.dateRange[0]
      params.endDate = filters.dateRange[1]
    }
    
    const response = await api.get('/organizer/feedbacks', { params })
    const data = response.data.data
    
    feedbacks.value = data.data || []
    pagination.total = data.total || 0
    
  } catch (error) {
    console.error('加载反馈列表失败:', error)
    ElMessage.error('加载反馈列表失败')
  } finally {
    loading.value = false
  }
}

const resetFilters = () => {
  Object.assign(filters, {
    keyword: '',
    activityId: '',
    type: '',
    rating: '',
    status: '',
    dateRange: null
  })
  pagination.current = 1
  loadFeedbacks()
}

const viewFeedback = (feedback) => {
  currentFeedback.value = feedback
  detailDialogVisible.value = true
  
  // 如果是未读状态，自动标记为已读
  if (feedback.status === 'unread') {
    markAsRead(feedback.id, false)
  }
}

const closeDetailDialog = () => {
  detailDialogVisible.value = false
  currentFeedback.value = null
}

const replyFeedback = (feedback) => {
  currentFeedback.value = feedback
  replyForm.content = ''
  replyDialogVisible.value = true
}

const confirmReply = async () => {
  if (!replyForm.content.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }
  
  try {
    replying.value = true
    
    await api.post(`/organizer/feedbacks/${currentFeedback.value.id}/reply`, {
      content: replyForm.content
    })
    
    ElMessage.success('回复发送成功')
    replyDialogVisible.value = false
    loadFeedbacks()
    loadStats()
    closeDetailDialog()
    
  } catch (error) {
    console.error('发送回复失败:', error)
    ElMessage.error('发送回复失败')
  } finally {
    replying.value = false
  }
}

const markAsRead = async (id, showMessage = true) => {
  try {
    await api.put(`/organizer/feedbacks/${id}/read`)
    
    if (showMessage) {
      ElMessage.success('已标记为已读')
    }
    
    // 更新本地状态
    const feedback = feedbacks.value.find(f => f.id === id)
    if (feedback) {
      feedback.status = 'read'
    }
    
    if (currentFeedback.value && currentFeedback.value.id === id) {
      currentFeedback.value.status = 'read'
    }
    
    loadStats()
    
  } catch (error) {
    console.error('标记已读失败:', error)
    if (showMessage) {
      ElMessage.error('标记已读失败')
    }
  }
}

const markAllAsRead = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要将所有未读反馈标记为已读吗？',
      '批量标记已读',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.put('/organizer/feedbacks/mark-all-read')
    
    ElMessage.success('已全部标记为已读')
    loadFeedbacks()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量标记已读失败:', error)
      ElMessage.error('批量标记已读失败')
    }
  }
}

const exportFeedbacks = () => {
  ElMessage.info('数据导出功能开发中...')
}

onMounted(() => {
  loadStats()
  loadActivities()
  loadFeedbacks()
})
</script>

<style scoped>
.feedback-management {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.header-actions {
  margin-left: 20px;
}

.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  height: 100px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  font-size: 28px;
  opacity: 0.3;
  color: #409eff;
}

.stat-icon.unread {
  color: #e6a23c;
}

.stat-icon.replied {
  color: #67c23a;
}

.stat-icon.rating {
  color: #f56c6c;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.list-card {
  min-height: 400px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 600;
  color: #303133;
}

.loading-container,
.empty-container {
  padding: 40px;
  text-align: center;
}

.feedback-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.feedback-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.feedback-item:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.feedback-item.unread {
  border-left: 4px solid #e6a23c;
  background: #fefefe;
}

.feedback-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.feedback-meta {
  display: flex;
  align-items: center;
  gap: 16px;
}

.student-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.student-name {
  font-weight: 600;
  color: #303133;
}

.student-id {
  font-size: 12px;
  color: #909399;
}

.feedback-time {
  font-size: 12px;
  color: #909399;
}

.feedback-content {
  margin-bottom: 16px;
}

.activity-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.activity-title {
  font-weight: 600;
  color: #409eff;
}

.feedback-rating {
  margin-bottom: 12px;
}

.feedback-text {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 12px;
}

.feedback-images {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.feedback-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.more-images {
  width: 60px;
  height: 60px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
}

.feedback-reply {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
  margin-top: 12px;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.reply-time {
  margin-left: auto;
  font-size: 12px;
  color: #909399;
}

.reply-content {
  color: #303133;
  line-height: 1.5;
}

.feedback-actions {
  display: flex;
  gap: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.feedback-detail {
  margin-bottom: 20px;
}

.feedback-content-detail {
  line-height: 1.6;
  color: #303133;
}

.feedback-images-detail {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.detail-image {
  width: 80px;
  height: 80px;
  border-radius: 6px;
}

.reply-content-detail {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  line-height: 1.6;
  color: #303133;
}

.reply-form {
  margin-bottom: 20px;
}

.original-feedback {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.original-feedback h4 {
  margin: 0 0 12px 0;
  color: #303133;
}

.original-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.original-text {
  color: #606266;
  line-height: 1.6;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-actions {
    margin-left: 0;
  }
  
  .filter-form {
    flex-direction: column;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .list-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .feedback-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .feedback-meta {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .activity-info {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .feedback-actions {
    flex-wrap: wrap;
  }
  
  .feedback-images-detail {
    gap: 8px;
  }
  
  .detail-image {
    width: 60px;
    height: 60px;
  }
}
</style>